package org.bim.view.drag.design.exception;


import lombok.Getter;
import org.bim.view.drag.design.util.ErrorCodeUtil;

/**
 * 基础异常
 * 用于封装公共的调用方法
 */
public class BizCommonException extends RuntimeException implements CommonException {
    public static final int CODE = DEFAULT;
    @Getter
    protected int code;
    @Getter
    protected String msg;

    public BizCommonException() {
        super(ErrorCodeUtil.getErrorMessage(CODE));
        this.code = CODE;
        this.msg = ErrorCodeUtil.getErrorMessage(getDefaultCode());
    }

    public BizCommonException(int code) {
        super(ErrorCodeUtil.getErrorMessage(code, CODE));
        this.code = code;
        this.reCorrectCode(code);
        this.msg = ErrorCodeUtil.getErrorMessage(this.code, getDefaultCode());
    }

    public BizCommonException(String msg, int code) {
        super(msg);
        this.code = code;
        this.reCorrectCode(code);
        this.msg = msg;
    }

    public BizCommonException(String msg) {
        super(msg);
        this.code = CODE;
        this.msg = msg;
    }

    public BizCommonException(int code, Exception ex) {
        super(ex);
        this.code = code;
        this.reCorrectCode(code);
        this.msg = ex.getMessage();
    }

    public BizCommonException(Exception ex) {
        super(ex);
        this.code = CODE;
        this.msg = ex.getMessage();
    }

    /**
     * @param code   异常码
     * @param params 错误信息模板中的参数
     */
    public BizCommonException(int code, String... params) {
        super(ErrorCodeUtil.getErrorMessage(code, CODE, params));
        this.code = code;
        this.reCorrectCode(code);
        this.msg = ErrorCodeUtil.getErrorMessage(this.code, getDefaultCode(), params);
    }

    public static BizCommonException build(int code) {
        return new BizCommonException(code);
    }

    public static BizCommonException buildByTemplate(int code, String... params) {
        return new BizCommonException(code, params);
    }

    @Override
    public boolean checkCode(int code) {
        return code >= -1 && code != 0;
    }

    public int getDefaultCode() {
        return DEFAULT;
    }

    /**
     * 校正code，若不想要code被校正，则可集成 {@link #checkCode(int)}并返回true
     *
     * @param code
     */
    private void reCorrectCode(int code) {
        if (!checkCode(code)) {
            this.code = getDefaultCode();
        }
    }
}
